package com.yuanchu.store.controller;

import com.yuanchu.common.utils.R;
import com.yuanchu.common.validator.ValidationGroups;
import com.yuanchu.store.dto.EditCartParamsDto;
import com.yuanchu.store.service.YoshopCartService;
import com.yuanchu.store.utils.SecurityUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-01-27 20:45
 */
@RestController
@RequestMapping("cart")
public class ShopCartController {

    @Resource
    private YoshopCartService shopCartService;

    @GetMapping("total")
    public R queryCartTotal() {
        Integer userId = SecurityUtil.getUserId();
        int count = shopCartService.queryUserCartCount(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", count);
        return R.ok().put("data", map);
    }

    @ApiOperation("查询用户购物车")
    @GetMapping("/list")
    public R queryUserCart() {
        Integer userId = SecurityUtil.getUserId();
        Map<String, Object> list = shopCartService.queryUserCart(userId);
        return R.ok().put("data", list);
    }

    /**
     * 修改购物车
     * /cart/update
     * @param param
     * @return
     */
    @PostMapping("/update")
    public R updateCart(@RequestBody @Validated({ValidationGroups.Update.class}) EditCartParamsDto param) {
        Integer userId = SecurityUtil.getUserId();
        Integer cartTotal = shopCartService.updateCartById(userId, param);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", cartTotal);
        return R.ok().put("data", map);
    }
    @PostMapping("/clear")
    public R clearCart(@RequestBody @Validated({ValidationGroups.Delete.class}) EditCartParamsDto param) {
        Integer userId = SecurityUtil.getUserId();
        Integer storeId = 10001;
        Integer cartTotal = shopCartService.clearCart(userId, param.getCartIds(), storeId);
        Map<String, Object> map = new HashMap<>();
        map.put("cartTotal", cartTotal);
        return R.ok().put("data", map);
    }
    @PostMapping("/del")
    public R delCartGoods(Integer userId, String cartIds, int storeId) {
        boolean delCartGoods = shopCartService.delCartGoods(userId, cartIds, storeId);
        if (!delCartGoods){
            return R.error("删除购物车失败");
        }
        return R.ok();
    }
    @ApiOperation("添加购物车")
    @PostMapping("/add")
    public R addCart(@RequestBody @Validated({ValidationGroups.Insert.class}) EditCartParamsDto param) {
        Integer userId = SecurityUtil.getUserId();

        shopCartService.addCart(userId, param);
        return R.ok();
    }
}
